<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>将json数组打印变成字符串</title>
</head>

<body>
    <script>
        const posts = [
            { title: 'A', author: 'a', id: 1 },
            { title: 'B', author: 'b', id: 2 }
        ]

        // localStorage.setItem('posts', JSON.stringify(posts))
        const authors = [
            {
                name: 'b', hometown: '鄱阳', bio: '腾讯'
            }
        ]

        function getPostById(id) {
            // 根据id 找文章
            // const post = posts.find(post => post.id === id);

            // const { author } = post; //结构出author
            // console.log(authors.find(item => item.name == author))
            // return post;
            return new Promise((resolve, reject) => {// 返回一个promise实例
                // resolve()
                console.log('--------')
                setTimeout(() => { //直接写resolve没有意思 一般封装一个耗时任务
                    const post = posts.find(post => post.id == id)
                    console.log(post);
                    if (post) {
                        resolve(post)
                    } else {
                        let err = new Error('没有数据')
                        reject(err)
                    }
                }, 200)
            })
        }
        getPostById(3)
            .then((data) => {
                console.log(data, '///////////////////')
            })
            .catch((e) => {
                console.log(e.message)
            })
    </script>
</body>

</html>